const jwt = require('jsonwebtoken');

class JWTConfig {
  constructor() {
    this.secret = process.env.JWT_SECRET || 'default-secret-change-in-production';
    this.refreshSecret = process.env.JWT_REFRESH_SECRET || 'default-refresh-secret-change-in-production';
    this.expiresIn = process.env.JWT_EXPIRES_IN || '24h';
    this.refreshExpiresIn = process.env.JWT_REFRESH_EXPIRES_IN || '7d';
  }

  // 生成访问令牌
  generateAccessToken(payload) {
    return jwt.sign(payload, this.secret, {
      expiresIn: this.expiresIn,
      issuer: 'saas-backend',
      audience: 'saas-frontend'
    });
  }

  // 生成刷新令牌
  generateRefreshToken(payload) {
    return jwt.sign(payload, this.refreshSecret, {
      expiresIn: this.refreshExpiresIn,
      issuer: 'saas-backend',
      audience: 'saas-frontend'
    });
  }

  // 验证访问令牌
  verifyAccessToken(token) {
    try {
      return jwt.verify(token, this.secret, {
        issuer: 'saas-backend',
        audience: 'saas-frontend'
      });
    } catch (error) {
      throw new Error(`Invalid access token: ${error.message}`);
    }
  }

  // 验证刷新令牌
  verifyRefreshToken(token) {
    try {
      return jwt.verify(token, this.refreshSecret, {
        issuer: 'saas-backend',
        audience: 'saas-frontend'
      });
    } catch (error) {
      throw new Error(`Invalid refresh token: ${error.message}`);
    }
  }

  // 生成令牌对
  generateTokenPair(user) {
    const payload = {
      sub: user._id.toString(),
      tenantId: user.tenantId,
      email: user.email,
      role: user.role
    };

    const accessToken = this.generateAccessToken(payload);
    const refreshToken = this.generateRefreshToken({ 
      sub: user._id.toString(),
      tenantId: user.tenantId 
    });

    return {
      accessToken,
      refreshToken,
      expiresIn: this.expiresIn,
      tokenType: 'Bearer'
    };
  }

  // 从令牌中提取租户ID
  extractTenantId(token) {
    try {
      const decoded = this.verifyAccessToken(token);
      return decoded.tenantId;
    } catch (error) {
      return null;
    }
  }

  // 从令牌中提取用户信息
  extractUserInfo(token) {
    try {
      const decoded = this.verifyAccessToken(token);
      return {
        userId: decoded.sub,
        tenantId: decoded.tenantId,
        email: decoded.email,
        role: decoded.role
      };
    } catch (error) {
      return null;
    }
  }

  // Fastify JWT 插件配置
  getFastifyJWTConfig() {
    return {
      secret: this.secret,
      sign: {
        expiresIn: this.expiresIn,
        issuer: 'saas-backend',
        audience: 'saas-frontend'
      },
      verify: {
        issuer: 'saas-backend',
        audience: 'saas-frontend'
      }
    };
  }
}

module.exports = new JWTConfig();